//
//  MCMenuTable.swift
//  swiftOfAfn
//
//  Created by Mikey on 16/10/19.
//  Copyright © 2016年 mikey. All rights reserved.
//

import UIKit

class MCMenuTable: UIView, UIScrollViewDelegate {

    var scrollEnabled = true
    
    let scrollView = UIScrollView()
    
    var currentPage = 0
    
    var views = [UIView]()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        initView()
    }
    
    private func initView() {
        scrollView.frame = bounds
        scrollView.backgroundColor = UIColor.white
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.isPagingEnabled = true
        scrollView.delegate = self
        scrollView.scrollsToTop = false
        addSubview(scrollView)
    }
    
    public func addSubViews(arr: [UIView]) {
        views = arr
        loadScrollViewWithPage(page: 0)
        scrollView.contentSize = CGSize(width: bounds.width * CGFloat(views.count), height: 0)
    }
    
    func loadScrollViewWithPage(page: Int) {
        let view = views[page]
        currentPage = page
        var frame = scrollView.frame
        frame.origin.x = frame.width * CGFloat(page)
        frame.origin.y = 0
        view.frame = frame
        scrollView.addSubview(view)
        if scrollView.contentOffset.x != frame.origin.x {
            scrollView.setContentOffset(CGPoint(x:frame.origin.x, y:0), animated: true)
        }
        
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let pageWidth = scrollView.bounds.width
        let page = ((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1
        currentPage = Int(page)
        
        
        if currentPage >= 0 && currentPage <= views.count - 1 {
            loadScrollViewWithPage(page: currentPage)
        }
        
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
